<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\WechatAuthorization;
use App\Models\WechatUser;
use App\Contant\UserGender;
class WechatAuthController extends Controller
{
    public function __construct(){

    }

    public function authLogin(Request $request){

        $appid = config('wechat.oauth.appid');
        $url = config('wechat.oauth.wechat_auth_url');
        $callback_url = config('wechat.oauth.callback_url');
        $state = $this->getState();
        $open_url = "$url?appid=$appid&redirect_uri=$callback_url&response_type=code&scope=snsapi_userinfo&state=$state&connect_redirect=1#wechat_redirect";

        header('location:'.$open_url);
    }

    public function wechatCallback(Request $request){
        $code = $request->input('code');
        $appid = config('wechat.oauth.appid');
        $appSecret = config('wechat.oauth.app_secret');
        $url = config('wechat.oauth.wechat_access_token_url');
        $access_user_url = config('wechat.oauth.wechat_access_user_url');
        $token_url = "$url?appid=".$appid.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));

        if (isset($token->errcode)) {
            logger()->info($token->errcode.':'.$token->errmsg);
            return $this->getMessage($token->errcode,$token->errmsg);
        }

        logger()->info(file_get_contents($token_url));
        $user_info_url = "$access_user_url?access_token=".$token->access_token.'&openid='.$token->openid.'&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url));

        if (isset($user_info->errcode)) {
            logger()->info($user_info->errcode.':'.$user_info->errmsg);
            return $this->getMessage($user_info->errcode,$user_info->errmsg);
        }
        $this->userAuthorized($token,$user_info);
        logger()->info(json_encode($user_info));
        return redirect('http://admin.saipujianshen.com');
    }

    /*
     * 处理用户授权信息
     */
    public function userAuthorized($token,$user_info){
        if(WechatAuthorization::where('openid',$token->openid)->first())
            return ;

        DB::beginTransaction();
        try{

            $authorize = new WechatAuthorization();
            $authorize->access_token = $token->access_token;
            $authorize->expires_in = $token->expires_in;
            $authorize->refresh_token = $token->refresh_token;
            $authorize->openid = $token->openid;
            $authorize->save();

            $wechatUser = new WechatUser();
            $wechatUser->openid =  $user_info->appid;
            $wechatUser->nickname = $user_info->nickname;
            $wechatUser->sex = $user_info->sex;
            $wechatUser->province = $user_info->province;
            $wechatUser->city = $user_info->city;
            $wechatUser->country = $user_info->country;
            $wechatUser->headimgurl = $user_info->headimgurl;
            $wechatUser->privilege = $user_info->privilege;

            $wechatUser->save();
            $user = new User();
            $user->name = $user_info->nickname;
            $user->sex = UserGender::trans($user_info->sex);
            $user->avatar = $user_info->headimgurl;
            $user->openid = $user_info->openid;
            $user->save();
            DB::commit();
            return true;
        }catch(\Exception $e){
            logger()->error($e->getMessage);
            DB::rollback();
            return false;
        }
    }
    /*
     * 获取state随机数
     */
    private function getState(){
        $chars = ['a','b','c','d','e','f','g
        ','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
        $num = mt_rand(10000,99999);

        return $chars[mt_rand(0,25)].$chars[mt_rand(0,25)].$chars[mt_rand(0,25)].$chars[mt_rand(0,25)].$chars[mt_rand(0,25)].$num;
    }
}
